<template>
  <div
    class="smart-plan-list-container common-list-container"
    v-infinite-scroll="loadData"
    :infinite-scroll-disabled="scrollDisabled"
  >
    <div class="smart-plan-list-top mar-b-12">
      <div class="smart-plan-list-top__left">
        <div class="top-title1 mar-b-8">{{ $t('smartPlan.title') }}</div>
        <div class="top-title2 mar-b-8">{{ $t('smartPlan.title2') }}</div>
        <el-button @click="openUrl">{{ $t('task.setting.taskTypeSetting.flow.components.title22') }}</el-button>
      </div>
      <div class="smart-plan-list-top__right">
        <img :src="img1" />
      </div>
    </div>
    <div class="smart-plan-list-header">
      <div class="smart-plan-list-header__left flex-x">
        <el-button class="smart-plan-list-header__button" v-if="hasCreateAuth" type="primary" @click="showCreateSmartPlanDialog">{{ $t('smartPlan.createPlan') }}</el-button>
      </div>
      <div class="smart-plan-list-header__right flex-x">
        <el-cascader
          class="mar-r-16 width-180"
          :props="propsConfig"
          v-model="planTypeArr"
          clearable
          :placeholder="$t('common.placeholder.selectSomething', {0: $t('smartPlan.businessObj')})"
        ></el-cascader>
        <!-- 创建维度筛选   -->
        <el-select class="mar-r-16 width-180" v-model="createDimension" clearable  :placeholder="$t('common.placeholder.selectSomething', {0: $t('common.smartPlan.createDimension')})">
          <el-option
            v-for="item in createDimensionsList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-select class="mar-r-16 width-180" v-model="planStatus" :placeholder="$t('common.placeholder.select')">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-input class="smart-plan-list-header__search-input" :placeholder="$t('smartPlan.searchPlaceholder')" v-model="keyword" @keyup.enter.native="search">
          <template slot="append"><el-button type="primary" @click="search">{{ $t('common.base.search') }}</el-button></template>
        </el-input>
      </div>
    </div>
    <div
      class="smart-plan-list-content"
      v-loading="loading"
      v-infinite-scroll="loadData"
      :infinite-scroll-disabled="scrollDisabled"
    >
      <template v-if="planList.length">
        <div class="smart-plan-list-items">
          <div
            class="smart-plan-list-item mar-r-16 mar-b-16"
            v-for="(item, index) in planList"
            :key="index"
            @click="openDetailTab(item.id)"
          >
            <div class="smart-plan-list-item__left">
              <i class="iconfont" :class="[iconClassEnum1[item.planType]]"></i>
            </div>
            <div class="smart-plan-list-item__right">
              <div class="smart-plan-list-item__title">
                <div class="plan-title">{{ item.planName }}</div>
                <div class="plan-status" :class="[statusClassMap[item.planStatus]]"><span></span>{{ getStatusName(item.planStatus) }}</div>
              </div>
              <div class="smart-plan-list-item__type mar-b-10">
                <div class="plan-type mar-r-8" v-if="item.planType != 'PAAS'"><i class="iconfont" :class="[iconClassEnum2[item.planType]]"></i><span>{{ getModuleTypeName(item.planType) }}</span></div>
                <div class="plan-type"><i class="iconfont" :class="[iconClassEnum3[item.planType]]"></i><span>{{ item.planTypeName }}</span></div>
              </div>
              <div class="smart-plan-list-item__type">
                <div class="plan-type mar-r-8"><i class="iconfont icon-jishi"></i><span>{{ $t('smartPlan.runDays', {num: item.runTime || 0}) }}</span></div>
                <div class="plan-type"><i class="iconfont icon-zhanbi"></i><span>{{ item.runNumber }}{{ item.totalNumber ? `/${item.totalNumber}` : '' }}</span></div>
              </div>
            </div>
          </div>
        </div>
        <div class="all-loaded" v-if="noMore"><span class="mar-r-8">—</span>{{ $t('smartPlan.allLoaded') }}<span class="mar-l-8">—</span></div>
      </template>
      <no-data-view-new v-if="planList.length == 0 && !loading"></no-data-view-new>
    </div>

    <!-- 新建计划弹窗 -->
    <createSmartPlanDialog ref="createSmartPlanDialog" />
  </div>
</template>

<script>
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { openAccurateTab } from '@src/util/platform'
import createSmartPlanDialog from './components/createSmartPlanDialog'
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import { getAppList, getModuleList, getPageList, checkPlanTask } from '@src/modules/smartPlan/api/index.js'
import SmartPlanMixin from '@src/modules/smartPlan/mixin/index.js'
import { t } from '@src/locales'
import { getUserGuideStorageBase, setUserGuideStorageBase } from 'src/util/guideStorage.ts';
import { getOssUrl } from '@src/util/assets'
const img1 = getOssUrl('/smartPlan/image.png')
const SMART_PLAN_GUIDE = 'smart-plan-list-content-guide'
const SMART_PLAN_GUIDE_2 = 'smart-plan-list-content-guide-2'

export default {
  name: 'SmartPlanList',
  mixins: [SmartPlanMixin],
  data() {
    return {
      img1,
      loading: false,
      isFirstLoad: true,
      planList: [], // 智能计划列表数据
      planTypeArr: [],
      limit: 100,
      statusList: [{
        label: t('common.base.all'),
        value: ''
      }, {
        label: t('common.base.processing'),
        value: 0
      }, {
        label: t('common.base.usualStatus.finish'),
        value: 1
      }, {
        label: t('common.base.usualStatus.canceled'),
        value: 2
      }],
      createDimensionsList: [
       {
          label: t('common.smartPlan.createByProductDimension'),
          value: 0
        }, {
          label: t('common.smartPlan.createByCustomerDimension'),
          value: 1
        }
      ],
      moduleType: '',
      planStatus: '',
      createDimension: '', // 创建维度
      keyword: '',
      pageNum: 0,
      pageSize: 30,
      noMore: false,
      total: 0,
      propsConfig: {
        lazy: true,
        label: 'name',
        value: 'formId',
        lazyLoad: this.lazyLoad
      },
      iconClassEnum1: {
        'TASK': 'icon-gongdanjihua',
        'EVENT': 'icon-shijianjihua',
        'PAAS': 'icon-Paas',
        'ACTIVITY_RESEARCH': 'icon-tiaoyan1',
      },
      iconClassEnum2: {
        'TASK': 'icon-danzi',
        'EVENT': 'icon-fuwushijian',
        'ACTIVITY_RESEARCH': 'icon-huodong',
      },
      iconClassEnum3: {
        'TASK': 'icon-wendang',
        'EVENT': 'icon-wendang',
        'PAAS': 'icon-yingyong',
        'ACTIVITY_RESEARCH': 'icon-moban',
      },
    }
  },
  computed: {
    scrollDisabled() {
      return this.loading || this.noMore
    }
  },
  mounted() {
    this.search();
    window.__exports__refresh = async () => {
      this.search();
    }
  },
  methods: {
    search() {
      if (this.loading) return
      this.pageNum = 0
      this.planList = []
      this.noMore = false
      this.loadData()
    },
    loadData() {
      const pageNum = this.pageNum + 1
      this.getList(pageNum)
    },
    showCreateSmartPlanDialog() {
      if (this.total >= this.limit) {
        return this.$platform.alert(t('smartPlan.tips.tip3', {limit: this.limit}))
      }
      this.$refs.createSmartPlanDialog.open()
    },
    buildParams(pageNum) {
      let planType = this.planTypeArr[0]?.split('__')[0] || ''
      let planTypeId = this.planTypeArr[1] || ''
      // 如果选中的数据只有一个，说明是没有第二级数据，传参特殊处理
      if (this.planTypeArr.length == 1) {
        planTypeId = this.planTypeArr[0].split('__')[1] || ''
      }
      return {
        planType,
        planTypeId,
        planStatus: this.planStatus,
        createDimension: this.createDimension,
        pageSize: this.pageSize,
        pageNum: pageNum || 1,
        keyword: this.keyword,
      }
    },
    getList(pageNum) {
      const params = this.buildParams(pageNum)
      this.loading = true
      getPageList(params).then(res => {
        // 页面首次加载初始化引导
        if (this.isFirstLoad) {
          this.initSmartPlanGuide()
        }
        this.loading = false
        this.isFirstLoad = false
        this.pageNum++
        const list = res.data?.list || []
        if (list.length) {
          this.planList = [...this.planList, ...list]
        }
        this.noMore = res.data?.isLastPage
        this.total = res.data?.total || 0
        this.limit = res.data.createLimit || 100
      })
    },
    lazyLoad(node, resolve) {
      const { level } = node;
      // 动态节点
      const nodes = [];
      if (level == 0) {
        getAppList().then(res => {
          let data = (res?.data || []).map(item => {
            item.formId = item.type
            if (item.type == 'PAAS') {
              item.formId = `${item.type}__${item.paasAppId}`
            }
            return item
          })
          data.forEach(item => {
            nodes.push(item);
          })
          // resolve 节点返回
          resolve(nodes);
        })
      } else if (level == 1) {
        getModuleList({
          bizType: node.data.formId.split('__')[0],
          paasAppId: node.data.paasAppId
        }).then(res => {
          let data = res?.data || []
          data.forEach(item => {
            let obj = {
              ...item,
              leaf: node.level >= 1 
            }
            nodes.push(obj);
          })
          // resolve 节点返回
          resolve(nodes);
        })
      }
    },
    openDetailTab(planId) {
      if (!planId || !this.hasViewAuth) return
      let fromId = window.frameElement?.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSmartPlanDetail,
        params: `planId=${planId}`,
        fromId
      })
    },
    // 跳转智能计划使用说明
    openUrl() {
      this.$platform.openLink('https://doc.shb.ltd/shb_xoqazk/eka8tf9wv8x43arx/nxzgsum3qw5z6q5f.html')
    },
    // 智能计划引导
    async initSmartPlanGuide() {
      // 判断是否存在历史数据
      const res = await checkPlanTask()
      if (!res.data) {
        this.initSmartPlanGuide2()
        return
      }
      // 判断是否完成
      let id = SMART_PLAN_GUIDE
      let userGuideStorage = await getUserGuideStorageBase()
      let isComplete = userGuideStorage?.[id]?.isComplete
      if (isComplete) {
        this.initSmartPlanGuide2()
        return
      }
      this.$nextTick(() => {
        this.smartPlanGuide()
      })
    },
    smartPlanGuide() {
      let id = SMART_PLAN_GUIDE
      let lastFinish = 1;
      let arr = [
        {
          title: this.$t('common.guide.smartPlan.content4'),
          content: this.$t('common.guide.smartPlan.content5'),
          haveStep: false,
          nowStep: 1,
          id,
          domObj: () => {
            return document.querySelector('.smart-plan-list-content');
          },
          needCover: true,
          lastFinish,
          stepTotalSetting:{
            finishBtn: this.$t('common.base.iKnow'),
          }
        }
      ]
      this.$Guide(arr, 0, '', e => {
        return new Promise((resolve, reject) => {
          this.initSmartPlanGuide2()
          resolve();
        });
      })
        .create()
        .then(vueDom => {
          if (vueDom) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: id,
                  step: 1,
                  isComplete: 1
                }
              ]
            });
          }
        });
    },
    async initSmartPlanGuide2() {
      // 判断是否完成
      let id = SMART_PLAN_GUIDE_2
      let userGuideStorage = await getUserGuideStorageBase()
      let isComplete = userGuideStorage?.[id]?.isComplete
      if (isComplete) return
      this.$nextTick(() => {
        this.smartPlanGuide2()
      })
    },
    smartPlanGuide2() {
      let id = SMART_PLAN_GUIDE_2
      let lastFinish = 1;
      let arr = [
        {
          content: this.$t('common.guide.smartPlan.content6'),
          haveStep: false,
          nowStep: 1,
          id,
          domObj: () => {
            return document.querySelector('.smart-plan-list-header__button');
          },
          lastFinish,
          stepTotalSetting:{
            finishBtn: this.$t('common.base.iKnow'),
          }
        }
      ]
      this.$Guide(arr, 0, '', e => {
        return new Promise((resolve, reject) => {
          resolve();
        });
      })
        .create()
        .then(vueDom => {
          if (vueDom) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: id,
                  step: 1,
                  isComplete: 1
                }
              ]
            });
          }
        });
    },
  },
  components: {
    createSmartPlanDialog,
    NoDataViewNew,
  }
}
</script>

<style lang="scss" scoped>
.smart-plan-list {
  &-container {
    overflow: auto;
  }
  &-top {
    height: 220px;
    background: url('@src/assets/img/smartPlan/bg.png') no-repeat center;
    background-size: 100% 100%;
    display: flex;
    justify-content: space-between;
    padding: 27px 48px 9px 23px;
    .top-title1 {
      font-size: 36px;
      font-weight: bold;
      @include text-ellipsis()
    }
    .top-title2 {
      font-size: 18px;
      color: #8C8C8C;
      @include text-ellipsis-2()
    }
    &__right {
      img {
        height: 100%;
      }
    }
  }
  &-header {
    display: flex;
    justify-content: space-between;
    padding: 16px 16px 6px;
    background: #fff;
    .width-180 {
      ::v-deep .el-input {
        width: 180px
      }
    }
    ::v-deep .el-input-group--append .el-input__inner {
      width: 240px;
    }

    &__search-input{
      ::v-deep .el-input-group__append{
        border-top-left-radius: 0 !important;
        border-bottom-left-radius: 0 !important;
      }
    }
  }
  &-content {
    padding: 6px 0px 16px 16px;
    background: #fff;
    min-height: calc(100% - 60px);
    .all-loaded {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #8C8C8C;
    }
    .app-nodata-view {
      margin: 0 auto;
    }
  }
  &-items {
    display: flex;
    flex-wrap: wrap;
  }
  &-item {
    height: 128px;
    display: flex;
    padding: 16px 24px;
    border: 1px solid #EBEDF0;
    max-width: calc(33.33% - 16px);
    min-width: calc(20% - 16px);
    cursor: pointer;
    &__left {
      width: 36px;
      height: 36px;
      border-radius: 2px;
      background: #EEF9F7;
      margin-right: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      .iconfont {
        color: $color-primary-light-6;
        font-size: 18px;
      }
    }
    &__right {
      width: calc(100% - 52px);
    }
    &__title {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      .plan-title {
        flex: 1;
        font-size: 16px;
        font-weight: 500;
        @include text-ellipsis();
      }
      .plan-status {
        display: flex;
        align-items: center;
        font-size: 12px;
        line-height: 20px;
        span {
          width: 7px;
          height: 7px;
          border-radius: 50%;
          margin-right: 4px;
        }
        &.processing {
          color: #1989FA;
          span {
            background: #1989FA;
          }
        }
        &.finished {
          color: #8C8C8C;
          span {
            background: #8C8C8C;
          }
        }
        &.canceled {
          color: #F56C6C;
          span {
            background: #F56C6C;
          }
        }
      }
    }
    &__type {
      display: flex;
      .plan-type {
        height: 24px;
        max-width: 44%;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 2px 10px;
        border-radius: 20px;
        border: 1px solid #DCDEE0;
        font-size: 12px;
        color: #666;
        .iconfont {
          color: $color-primary-light-6;
          font-size: 12px;
          margin-right: 4px;
        }
        .icon-jishi {
          color: #E6A23C;
        }
        .icon-zhanbi {
          color: #07C160;
        }
        span {
          @include text-ellipsis();
        }
      }
    }
  }
}
@media screen and (max-width: 1300px) {
  .smart-plan-list-item {
    width: calc(33.33% - 16px);
  }
}
@media screen and (min-width: 1301px) and (max-width: 1900px) {
  .smart-plan-list-item {
    width: calc(25% - 16px);
  }
}
@media screen and (min-width: 1901px) {
  .smart-plan-list-item {
    width: calc(20% - 16px);
  }
}
</style>